<template>
  <div class="nginx-config">
    <el-container class="config-container">
      <el-aside width="250px" class="config-aside">
        <div class="config-list">
          <div class="list-header">
            <h3>配置列表</h3>
            <el-button type="primary" size="small" @click="showCreateDialog">
              新建配置
            </el-button>
          </div>
          <div class="search-box">
            <el-input
              v-model="searchQuery"
              placeholder="搜索配置..."
              clearable
              prefix-icon="Search"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <el-scrollbar>
            <el-menu :default-active="currentConfig?.file_path" @select="handleSelect">
              <el-menu-item v-for="config in filteredConfigs" :key="config.file_path" :index="config.file_path">
                <el-tooltip :content="config.name" placement="right" :show-after="1000">
                  <div class="flex flex-col flex-1 gap-2">
                    <span class="config-name">{{ config.name }}</span>
                    <el-tag size="small" type="info" effect="light" v-if="searchQuery && getContentMatches(config)">
                        匹配位置: {{ getContentMatches(config) }}
                    </el-tag>
                  </div>
                </el-tooltip>
              </el-menu-item>
            </el-menu>
          </el-scrollbar>
        </div>
      </el-aside>

      <el-main class="config-main">
        <div v-if="currentConfig" class="config-editor">
          <div class="editor-header">
            <div class="header-left">
              <h2>{{ currentConfig.name }}</h2>
            </div>
            <div class="header-right">
              <el-button-group class="action-group flex justify-end flex-1 ">
                <el-button type="primary" :loading="loading" @click="handleTest">
                  <template #icon>
                    <el-icon>
                      <Check />
                    </el-icon>
                  </template>
                  测试配置
                </el-button>
                <el-button type="success" :loading="loading" @click="handleApply">
                  <template #icon>
                    <el-icon>
                      <RefreshRight />
                    </el-icon>
                  </template>
                  应用配置
                </el-button>
              </el-button-group>

              <el-divider direction="vertical" />

              <el-button-group>
                <el-button 
                  v-if="!shouldShowEditor"
                  type="warning" 
                  :loading="loading" 
                  @click="handleEdit"
                >
                  <template #icon>
                    <el-icon>
                      <Edit />
                    </el-icon>
                  </template>
                  {{ isEditing ? '取消' : '代码编辑' }}
                </el-button>
                <el-button type="danger" :loading="loading" @click="handleDelete">
                  <template #icon>
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </template>
                  删除
                </el-button>
              </el-button-group>
            </div>
          </div>

          <!-- 可视化配置信息 -->
          <div v-if="!isEditing && !shouldShowEditor" class="visual-config">
            <el-scrollbar>
              <!-- 更改计数和保存按钮 -->
              <div v-if="hasChanges" class="changes-bar flex flex-1 items-center">
                <div class="flex gap-2">
                  <el-alert v-if="changesCount > 0" type="warning" :title="`更改 ${changesCount} 处`" :closable="false"/>
                  <el-alert v-if="addUpstreamCount > 0" type="success" :title="`添加 ${addUpstreamCount} 个`" :closable="false"/>
                  <el-alert v-if="deleteUpstreamCount > 0" type="error" :title="`删除 ${deleteUpstreamCount} 个`" :closable="false"/>
                </div>
                <div class="changes-actions">
                  <el-button @click="previewChanges">预览更改</el-button>
                  <el-button @click="undoChanges" type="danger">撤销</el-button>
                  <el-button type="primary" :loading="loading" @click="saveChanges">
                    保存并应用
                  </el-button>
                </div>
              </div>

              <!-- 其他内容 -->
              <div class="visual-content">
                <!-- Upstream 配置 -->
                <div v-if="currentConfig.upstreams.length > 0" class="upstream-section">
                  <div class="upstream-header">
                    <div class="flex flex-row flex-1 gap-2 items-center">
                      <div>
                        <h3 class="m-0">负载均衡配置</h3>
                      </div>
                      <el-tag size="small" type="success">
                        {{ currentConfig.upstreams.length }} 个负载均衡
                      </el-tag>
                    </div>
                     <!-- 添加负载均衡 -->
                    <!-- <div>
                      <el-button type="primary" size="small" @click="showCreateUpstreamDialog">
                        <template #icon>
                          <el-icon>
                            <Plus />
                          </el-icon>
                        </template>
                        添加负载均衡
                      </el-button>
                    </div> -->
                  </div>
                  <div v-for="(upstream, index) in currentConfig.upstreams" :key="index" class="upstream-block">
                    <el-card class="upstream-card">
                      <template #header>
                        <div class="upstream-header">
                          <div class="flex flex-row flex-1 gap-2 items-center">
                            <span class="upstream-name">{{ upstream.name }}</span>
                            <el-tag size="small" type="success">
                              {{ upstream.servers.length }} 个服务器
                            </el-tag>
                          </div>
                          <el-button type="primary" size="small" @click="showCreateUpstreamDialog(upstream)">
                            <template #icon>
                              <el-icon>
                                <Plus />
                              </el-icon>
                            </template>
                          </el-button>
                        </div>
                      </template>

                      <el-table :data="upstream.servers" border stripe>
                        <el-table-column prop="address" label="服务器地址">
                          <template #default="{ row }">
                            <div class="server-address" :class="{ 'deleted': row.isDelete }">
                              <el-input 
                                v-model="row.address" 
                                placeholder="例如：127.0.0.1:8080"
                                @change="handleAddressChange(row, upstream)"
                                :disabled="row.isDelete"
                              />
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column prop="comment" label="备注">
                          <template #default="{ row }">
                            <el-input 
                              v-model="row.comment" 
                              placeholder="添加备注"
                              @change="handleCommentChange(row, upstream)"
                              :disabled="row.isDelete"
                            />
                          </template>
                        </el-table-column>
                        <el-table-column label="状态" width="80">
                          <template #default="{ row }">
                            <div class="cursor-pointer" :class="{ 'deleted': row.isDelete }" @click="handleServerDownStatusChange(row, upstream)">
                              <el-tag v-if="row.isDelete" size="small" type="info">已删除</el-tag>
                              <el-tag v-else-if="row.down" size="small" type="danger">离线</el-tag>
                              <el-tag v-else size="small" type="success">在线</el-tag>
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column label="备用" width="80">
                          <template #default="{ row }">
                            <div class="cursor-pointer" :class="{ 'deleted': row.isDelete }" @click="handleServerBackupChange(row, upstream)">
                              <el-tag v-if="row.isDelete" size="small" type="info">已删除</el-tag>
                              <el-tag v-else-if="row.backup" size="small" type="danger">备用</el-tag>
                              <el-tag v-else size="small" type="success">主要</el-tag>
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column prop="weight" label="权重" width="80">
                          <template #default="{ row }">
                            <el-input
                              v-model="row.weight" 
                              @change="handleWeightChange(row, upstream)"
                              :disabled="row.isDelete"
                            />
                          </template>
                        </el-table-column>
                        <el-table-column label="故障转移" width="400">
                          <template #default="{ row }">
                            <div class="failover-settings" :class="{ 'deleted': row.isDelete }">
                              <div class="flex flex-row flex-1 gap-2 items-center">
                                <span class="text-sm">最大失败：</span>
                                <el-input v-model="row.max_fails"
                                    placeholder="次数"
                                    @change="handleMaxFailsChange(row, upstream)"
                                    :disabled="row.isDelete"
                                  />
                              </div>
                              <div class="flex flex-row flex-1 gap-2 items-center">
                                <span class="text-sm">超时时间(s)：</span>
                                <el-input v-model="row.fail_timeout"
                                    placeholder="如: 30"
                                    @change="handleFailTimeoutChange(row, upstream)"
                                    :disabled="row.isDelete"
                                  />
                              </div>
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column label="操作" width="80">
                          <template #default="{ row, $index }">
                            <el-button
                              v-if="!row.isDelete"
                              type="danger"
                              size="small"
                              circle
                              @click="handleDeleteServer(row, upstream, $index)"
                            >
                              <el-icon><Delete /></el-icon>
                            </el-button>
                            <el-button
                              v-else
                              type="primary"
                              size="small"
                              circle
                              @click="handleRestoreServer(row)"
                            >
                              <el-icon><RefreshLeft /></el-icon>
                            </el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                    </el-card>
                  </div>
                </div>

                <!-- Server 配置 -->
                <div v-for="(server, index) in currentConfig.servers" :key="index" class="server-block">
                  <el-card class="server-card">
                    <template #header>
                      <div class="server-header">
                        <div class="server-title">
                          <span class="domain-name">
                            {{ server.server_name.join(', ') || '默认服务器' }}
                          </span>
                          <el-tag :type="server.ssl ? 'success' : 'info'" size="small" class="ssl-tag">
                            {{ server.ssl ? 'HTTPS' : 'HTTP' }}
                          </el-tag>
                        </div>
                        <div class="server-ports">
                          <el-tag v-for="port in server.listen" :key="port" size="small" class="port-tag">
                            端口: {{ port }}
                          </el-tag>
                        </div>
                      </div>
                    </template>

                    <div class="locations">
                      <!-- Rewrite 规则 -->
                      <div v-if="server.rewrites?.length" class="rewrite-rules">
                        <el-descriptions title="重定向规则" :column="1" border size="small">
                          <el-descriptions-item v-for="(rewrite, rwIndex) in server.rewrites" :key="rwIndex" label="重定向规则">
                            <div class="rewrite-rule">
                              <el-tag size="small" type="warning">{{ rewrite.pattern }}</el-tag>
                              <el-icon><ArrowRight /></el-icon>
                              <el-tag size="small" type="success">{{ rewrite.replacement }}</el-tag>
                              <el-tag v-if="rewrite.flag" size="small" type="info">{{ rewrite.flag }}</el-tag>
                            </div>
                          </el-descriptions-item>
                        </el-descriptions>
                      </div>

                      <div v-for="(location, locIndex) in server.locations" :key="locIndex" class="location-block">
                        <el-descriptions :title="'路径: ' + (location.modifier ? location.modifier + ' ' : '') + location.path" :column="1" border>
                          <el-descriptions-item v-if="location.proxy_pass" label="反向代理" class="proxy-pass-item">
                            <el-tag size="small" type="success" class="proxy-pass-tag">{{ location.proxy_pass }}</el-tag>
                          </el-descriptions-item>

                          <!-- 添加 try_files 指令显示 -->
                          <el-descriptions-item v-if="location.try_files?.length" label="文件查找顺序">
                            <div class="try-files">
                              <el-tag v-for="(file, index) in location.try_files" :key="index" size="small" type="info" class="try-file-tag">
                                {{ file }}
                              </el-tag>
                            </div>
                          </el-descriptions-item>

                          <!-- 添加 add_header 指令显示 -->
                          <el-descriptions-item v-if="location.add_header" label="响应头">
                            <div class="headers">
                              <div v-for="(value, name) in location.add_header" :key="name" class="header-item">
                                <el-tag size="small" type="warning">{{ name }}</el-tag>
                                <span class="header-value">{{ value }}</span>
                              </div>
                            </div>
                          </el-descriptions-item>

                          <el-descriptions-item v-if="location.root" label="根目录">
                            {{ location.root }}
                          </el-descriptions-item>
                          <el-descriptions-item v-if="location.index && location.index.length" label="默认页面">
                            {{ location.index.join(', ') }}
                          </el-descriptions-item>

                          <!-- 代理请求头 -->
                          <el-descriptions-item v-if="location.proxy_headers?.length" label="代理请求头">
                            <el-table :data="location.proxy_headers" border size="small">
                              <el-table-column prop="name" label="名称" min-width="150">
                                <template #default="{ row }">
                                  <el-tag size="small" type="info">{{ row.name }}</el-tag>
                                </template>
                              </el-table-column>
                              <el-table-column prop="value" label="值" min-width="200">
                                <template #default="{ row }">
                                  <el-tag size="small" type="success">{{ row.value }}</el-tag>
                                </template>
                              </el-table-column>
                            </el-table>
                          </el-descriptions-item>

                          <!-- 代理超时设置 -->
                          <el-descriptions-item
                            v-if="location.proxy_connect_timeout || location.proxy_read_timeout || location.proxy_send_timeout"
                            label="代理超时设置">
                            <div class="proxy-timeouts">
                              <el-tag v-if="location.proxy_connect_timeout" size="small" type="info">
                                连接超时 : {{ location.proxy_connect_timeout }}
                              </el-tag>
                              <el-tag v-if="location.proxy_read_timeout" size="small" type="info">
                                读取超时: {{ location.proxy_read_timeout }}
                              </el-tag>
                              <el-tag v-if="location.proxy_send_timeout" size="small" type="info">
                                发送超时: {{ location.proxy_send_timeout }}
                              </el-tag>
                            </div>
                          </el-descriptions-item>

                          <!-- 代理缓冲设置 -->
                          <el-descriptions-item
                            v-if="location.proxy_buffer_size || location.proxy_buffers || location.proxy_busy_buffers_size"
                            label="代理缓冲设置">
                            <div class="proxy-buffers">
                              <el-tag v-if="location.proxy_buffer_size" size="small" type="info">
                                缓冲区大小: {{ location.proxy_buffer_size }}
                              </el-tag>
                              <el-tag v-if="location.proxy_buffers" size="small" type="info">
                                缓冲区数量: {{ location.proxy_buffers }}
                              </el-tag>
                              <el-tag v-if="location.proxy_busy_buffers_size" size="small" type="info">
                                忙碌缓冲区大小: {{ location.proxy_busy_buffers_size }}
                              </el-tag>
                            </div>
                          </el-descriptions-item>

                          <!-- 客户端设置 -->
                          <el-descriptions-item v-if="location.client_max_body_size || location.client_body_buffer_size"
                            label="客户端设置">
                            <div class="client-settings">
                              <el-tag v-if="location.client_max_body_size" size="small" type="info">
                                最大请求体: {{ location.client_max_body_size }}
                              </el-tag>
                              <el-tag v-if="location.client_body_buffer_size" size="small" type="info">
                                请求体缓冲区: {{ location.client_body_buffer_size }}
                              </el-tag>
                            </div>
                          </el-descriptions-item>

                          <!-- Location 包含的配置文件 -->
                          <el-descriptions-item v-if="location.includes?.length" label="包含的配置文件">
                            <el-tag v-for="include in location.includes" :key="include" size="small" type="info"
                              class="include-tag">
                              {{ include }}
                            </el-tag>
                          </el-descriptions-item>
                        </el-descriptions>
                      </div>
                    </div>

                    <div v-if="server.ssl" class="ssl-info">
                      <el-descriptions title="SSL 证书信息" :column="1" border size="small">
                        <el-descriptions-item label="证书文件">
                          {{ server.ssl_certificate }}
                        </el-descriptions-item>
                        <el-descriptions-item label="私钥文件">
                          {{ server.ssl_certificate_key }}
                        </el-descriptions-item>
                        <el-descriptions-item v-if="server.ssl_session_timeout" label="会话超时">
                          {{ server.ssl_session_timeout }}
                        </el-descriptions-item>
                        <el-descriptions-item v-if="server.ssl_ciphers" label="加密套件">
                          {{ server.ssl_ciphers }}
                        </el-descriptions-item>
                        <el-descriptions-item v-if="server.ssl_protocols" label="SSL 协议">
                          {{ server.ssl_protocols }}
                        </el-descriptions-item>
                        <el-descriptions-item v-if="server.ssl_prefer_server_ciphers !== undefined" label="优先使用服务器加密套件">
                          {{ server.ssl_prefer_server_ciphers ? '是' : '否' }}
                        </el-descriptions-item>
                      </el-descriptions>
                    </div>

                    <!-- 错误页面配置 -->
                    <div v-if="server.error_page" class="error-pages">
                      <el-descriptions title="错误页面配置" :column="1" border size="small">
                        <el-descriptions-item v-for="(page, codes) in server.error_page" :key="codes"
                          :label="'错误代码: ' + codes">
                          {{ page }}
                        </el-descriptions-item>
                      </el-descriptions>
                    </div>

                    <!-- 包含的配置文件 -->
                    <div v-if="server.includes?.length" class="includes">
                      <el-descriptions title="包含的配置文件" :column="1" border size="small">
                        <el-descriptions-item label="配置文件">
                          <el-tag v-for="include in server.includes" :key="include" size="small" type="info"
                            class="include-tag">
                            {{ include }}
                          </el-tag>
                        </el-descriptions-item>
                      </el-descriptions>
                    </div>
                  </el-card>
                </div>
              </div>
            </el-scrollbar>
          </div>

          <!-- 编辑器 -->
          <div v-else class="editor-content">
            <MonacoEditor
              v-model="editingContent"
              language="nginx"
              :readOnly="loading"
              class="config-editor"
            />
            <div class="editor-footer">
              <el-button 
                type="primary" 
                size="large"
                :loading="loading"
                @click="saveEdit"
              >
                <template #icon>
                  <el-icon><Check /></el-icon>
                </template>
                保存配置
              </el-button>
            </div>
          </div>
        </div>
        <el-empty v-else description="请选择或创建配置" />
      </el-main>

    </el-container>

    <!-- 创建配置对话框 -->
    <el-dialog v-model="createDialogVisible" title="新建配置" width="80%">
      <el-form ref="createFormRef" :model="createForm" :rules="createRules" label-width="100px">
        <el-form-item label="配置名称" prop="name">
          <el-input v-model="createForm.name" placeholder="请输入配置名称" />
        </el-form-item>
        <el-form-item label="配置内容" prop="content">
          <el-input v-model="createForm.content" type="textarea" :autosize="{ minRows: 10, maxRows: 25 }"
            placeholder="请输入配置内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate" :loading="loading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="删除确认" width="400px">
      <p>确定要删除配置 "{{ currentConfig?.name }}" 吗？此操作不可恢复。</p>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete" :loading="loading">
          确定删除
        </el-button>
      </template>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog v-model="previewDialogVisible" title="预览更改" width="800px" class="preview-dialog">
      <div class="preview-content">
        <el-tabs v-model="previewTab">
          <el-tab-pane label="当前配置" name="current">
            <pre class="config-preview">{{ previewContent }}</pre>
          </el-tab-pane>
          <el-tab-pane label="原始配置" name="original">
            <pre class="config-preview">{{ originalContent }}</pre>
          </el-tab-pane>
        </el-tabs>
      </div>
      <template #footer>
        <el-button @click="previewDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="saveChanges">保存更改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Check, RefreshRight, Edit, Delete, Plus, ArrowRight, Search, RefreshLeft } from '@element-plus/icons-vue'
import { NginxService, type NginxConfigInfo, type UpstreamConfig, type UpstreamServer } from '@/services/nginx.service'
import MonacoEditor from '@/components/MonacoEditor.vue'

// 状态管理
const configs = ref<NginxConfigInfo[]>([])
const currentConfig = ref<NginxConfigInfo | null>(null)
const loading = ref(false)

// 编辑状态
const isEditing = ref(false)
const editingContent = ref('')

// 创建配置表单
const createDialogVisible = ref(false)
const createFormRef = ref<FormInstance>()
const createForm = ref({
  name: '',
  content: ''
})

const createRules: FormRules = {
  name: [
    { required: true, message: '请输入配置名称', trigger: 'blur' },
    { min: 2, message: '配置名称不能少于2个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入配置内容', trigger: 'blur' }
  ]
}

// 删除确认对话框
const deleteDialogVisible = ref(false)

// 跟踪原始配置和修改后的配置
const originalConfig = ref<NginxConfigInfo | null>(null)
const hasChanges = ref(false)
const changesCount = ref(0)
const addUpstreamCount = ref(0)
const deleteUpstreamCount = ref(0)

// 预览对话框
const previewDialogVisible = ref(false)
const previewTab = ref('current')
const previewContent = ref('')
const originalContent = ref('')

// 搜索相关
const searchQuery = ref('')

// 过滤后的配置列表
const filteredConfigs = computed(() => {
  if (!searchQuery.value) return configs.value;
  
  const query = searchQuery.value.toLowerCase();
  return configs.value.filter(config => {
    return config.name.toLowerCase().includes(query) || 
           config.file_path.toLowerCase().includes(query) ||
           config.content.toLowerCase().includes(query);
  });
});

// 计算修改的数量
const updateChangesCount = () => {
  if (!currentConfig.value || !originalConfig.value) {
    changesCount.value = 0;
    hasChanges.value = false;
    return;
  }

  let count = 0;
  let deleteCount = 0;
  let addCount = 0;

  currentConfig.value.upstreams.forEach((upstream, uIndex) => {
    upstream.servers.forEach((server, sIndex) => {
      if (server.isAdd) {
        addCount++;
        return;
      }
      const originalServer = originalConfig.value?.upstreams[uIndex]?.servers[sIndex];
      if (originalServer) {
        if (server.isDelete) {
          deleteCount++;
        } else {
          if (server.down !== originalServer.down) count++;
          if (server.backup !== originalServer.backup) count++;
          if (server.comment !== originalServer.comment) count++;
          if (server.address !== originalServer.address) count++;
          if (server.weight !== originalServer.weight) count++;
          if (server.max_fails !== originalServer.max_fails) count++;
          if (server.fail_timeout !== originalServer.fail_timeout) count++;
        }
      }
    });
  });

  changesCount.value = count;
  addUpstreamCount.value = addCount;
  deleteUpstreamCount.value = deleteCount;
  hasChanges.value = count > 0 || addUpstreamCount.value > 0 || deleteUpstreamCount.value > 0;
}

// const showCreateUpstreamDialog = () => {
//   currentConfig.value?.upstreams.push({
//     name: 'newUpstream',
//     servers: [],
//   });
// }

const showCreateUpstreamDialog = (upstream: UpstreamConfig) => {
  console.log(upstream);
  upstream.servers.push({
    isAdd: true,
    address: '127.0.0.1:8080',
    weight: 1,
    backup: false,
    down: false,
    max_fails: 3,
  });
  // addUpstreamCount.value++;
  updateChangesCount();
}

// 处理服务器状态更改
const handleServerDownStatusChange = (row: UpstreamServer, upstream: UpstreamConfig) => {
  row.down = !row.down;
  if (!currentConfig.value) return;
  updateChangesCount();
}

// 处理服务器备用状态更改
const handleServerBackupChange = (row: UpstreamServer, upstream: UpstreamConfig) => {
  row.backup = !row.backup;
  if (!currentConfig.value) return;
  updateChangesCount();
}

// 处理备注更改
const handleCommentChange = (row: UpstreamServer, upstream: UpstreamConfig) => {
  if (!currentConfig.value) return;
  updateChangesCount();
}

// 处理服务器地址更改
const handleAddressChange = (row: UpstreamServer, upstream: UpstreamConfig) => {
  if (!currentConfig.value) return;
  // 验证地址格式
  const addressPattern = /^[a-zA-Z0-9\-\.]+(?::\d+)?$/;
  if (!addressPattern.test(row.address)) {
    ElMessage.warning('服务器地址格式不正确，请使用 host:port 格式');
    return;
  }
  updateChangesCount();
}

// 处理权重更改
const handleWeightChange = (row: UpstreamServer, upstream: UpstreamConfig) => {
  if (!currentConfig.value) return;
  updateChangesCount();
}

// 处理最大失败次数更改
const handleMaxFailsChange = (row: UpstreamServer, upstream: UpstreamConfig) => {
  if (!currentConfig.value) return;
  updateChangesCount();
}

// 处理故障超时时间更改
const handleFailTimeoutChange = (row: UpstreamServer, upstream: UpstreamConfig) => {
  if (!currentConfig.value) return;
  // 验证超时时间格式
  const timeoutPattern = /^\d+[smh]$/;
  if (row.fail_timeout && !timeoutPattern.test(row.fail_timeout)) {
    ElMessage.warning('超时时间格式不正确，请使用数字加单位(s/m/h)的格式，如: 30s');
    return;
  }
  updateChangesCount();
}

// 保存更改
const saveChanges = async () => {
  if (!currentConfig.value || !hasChanges.value) return;

  try {
    loading.value = true;
    // 生成新的配置内容
    const newContent = generateConfigContent(currentConfig.value);
    await NginxService.updateConfig(currentConfig.value.file_path, newContent);

    // 重新加载配置
    await loadConfigs();
  

    ElMessage.success('保存成功');
    handleApply();
  } catch (error) {
    ElMessage.error('保存失败');
    console.error('Failed to save changes:', error);
  } finally {
    loading.value = false;
  }
}

// 生成配置内容
const generateConfigContent = (config: NginxConfigInfo): string => {
  let content = '';

  // 生成 upstream 配置
  for (const upstream of config.upstreams) {
    content += `upstream ${upstream.name} {\n`;
    for (const server of upstream.servers) {
      // 跳过被标记为删除的服务器
      if (server.isDelete) continue;
      
      let serverLine = `    server ${server.address}`;
      if (server.weight) serverLine += ` weight=${server.weight}`;
      if (server.backup) serverLine += ' backup';
      if (server.down) serverLine += ' down';
      if (server.max_fails) serverLine += ` max_fails=${server.max_fails}`;
      if (server.fail_timeout) serverLine += ` fail_timeout=${server.fail_timeout}`;
      serverLine += ';';  // 先加分号
      if (server.comment) serverLine += ` #${server.comment}`; // 再加注释，注意分号后面加了空格
      content += serverLine + '\n';
    }
    content += '}\n\n';
  }

  // 从原始内容中提取非 upstream 的配置
  const originalLines = config.content.split('\n');
  let inUpstream = false;
  let upstreamBraceCount = 0;

  // 处理每一行，跳过 upstream 块
  for (const line of originalLines) {
    if (line.trim().startsWith('upstream ')) {
      inUpstream = true;
      upstreamBraceCount = 1;
      continue;
    }

    if (inUpstream) {
      if (line.includes('{')) upstreamBraceCount++;
      if (line.includes('}')) upstreamBraceCount--;
      if (upstreamBraceCount === 0) {
        inUpstream = false;
      }
      continue;
    }

    content += line + '\n';
  }

  return content.trim();
};

// 选择配置
const handleSelect = async (filePath: string) => {
  try {
    const selectedConfig = configs.value.find(c => c.file_path === filePath);
    if (selectedConfig) {
      currentConfig.value = selectedConfig;
      // 保存原始配置的副本
      originalConfig.value = JSON.parse(JSON.stringify(selectedConfig));
      editingContent.value = selectedConfig.content;
      hasChanges.value = false;
      changesCount.value = 0;
      // 根据是否有负载均衡服务器来设置编辑模式
      isEditing.value = shouldShowEditor.value;
    }
  } catch (error) {
    ElMessage.error('加载配置失败');
    console.error('Failed to load config:', error);
  }
}

// 测试配置
const handleTest = async () => {
  try {
    loading.value = true
    const result = await NginxService.testConfig()
    ElMessage.success(result.message)
  } catch (error) {
    ElMessage.error('配置测试失败')
    console.error('Failed to test config:', error)
  } finally {
    loading.value = false
  }
}

// 应用配置
const handleApply = async () => {
  try {
    loading.value = true
    const result = await NginxService.applyConfig()
    ElMessage.success(result.message)
  } catch (error) {
    ElMessage.error((error as any).response.data.message)
    console.error('Failed to apply config:', error)
  } finally {
    loading.value = false
  }
}

// 编辑配置
const handleEdit = () => {
  // 如果是自动切换到编辑模式的，不允许切回可视化模式
  if (shouldShowEditor.value) {
    ElMessage.warning('当前配置没有可视化的负载均衡服务器，只能使用代码编辑模式');
    return;
  }
  isEditing.value = !isEditing.value;
  editingContent.value = currentConfig.value?.content || '';
}


// 保存编辑
const saveEdit = async () => {
  if (!currentConfig.value) return

  try {
    loading.value = true
    await NginxService.updateConfig(currentConfig.value.file_path, editingContent.value)
    
    // 重新加载配置
    await loadConfigs();

    ElMessage.success('保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
    console.error('Failed to save config:', error)
  } finally {
    loading.value = false
  }
}

// 显示创建对话框
const showCreateDialog = () => {
  createForm.value = {
    name: '',
    content: `upstream server1 {
    server 127.0.0.1:8080; #服务器3
}
server {
        listen       80;
        server_name  localhost2.baidu.com;
        location / {
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header REMOTE-HOST $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://server1/;
        }
}`
  }
  createDialogVisible.value = true
}

// 创建配置
const handleCreate = async () => {
  if (!createFormRef.value) return

  try {
    await createFormRef.value.validate()
    loading.value = true
    const newConfig = await NginxService.createConfig(createForm.value.name, createForm.value.content)
    configs.value.push(newConfig)
    createDialogVisible.value = false
    ElMessage.success('创建成功')
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('创建失败')
    }
    console.error('Failed to create config:', error)
  } finally {
    loading.value = false
  }
}

// 删除配置
const handleDelete = async () => {
  if (currentConfig.value) {
    await ElMessageBox.confirm('确定要删除此配置吗？', '警告', {
      type: 'warning'
    });

    try {
      loading.value = true;
      await NginxService.deleteConfig(currentConfig.value.file_path);
      ElMessage.success('配置已删除');

      // 重新加载配置列表
      await loadConfigs();
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除配置失败');
        console.error(error);
      }
    } finally {
      loading.value = false;
    }
  }
}

// 加载所有配置
const loadConfigs = async () => {
  try {
    loading.value = true;
    configs.value = await NginxService.getAllConfigs();
    if (configs.value.length > 0) {

      // 如果当前配置不存在，则选中第一个配置
      if (currentConfig.value) {
        const updatedConfig = configs.value.find(c => c.file_path === currentConfig.value?.file_path);
        if (updatedConfig) {
          currentConfig.value = updatedConfig;
          originalConfig.value = JSON.parse(JSON.stringify(updatedConfig));
          editingContent.value = updatedConfig.content;
        }else{
          const firstConfig = configs.value[0];
          currentConfig.value = firstConfig;
          // 保存原始配置的副本
          originalConfig.value = JSON.parse(JSON.stringify(firstConfig));
          editingContent.value = firstConfig.content;
        }
      } else {
         // 选中第一个配置
        const firstConfig = configs.value[0];
        currentConfig.value = firstConfig;
        // 保存原始配置的副本
        originalConfig.value = JSON.parse(JSON.stringify(firstConfig));
        editingContent.value = firstConfig.content;
      }
     
      hasChanges.value = false;
      changesCount.value = 0;
      // 根据是否有负载均衡服务器来设置编辑模式
      isEditing.value = shouldShowEditor.value;
    }
  } catch (error) {
    ElMessage.error('加载配置列表失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 确认删除
const confirmDelete = async () => {
  if (!currentConfig.value) return

  try {
    loading.value = true
    await NginxService.deleteConfig(currentConfig.value.file_path)
    configs.value = configs.value.filter(c => c.file_path !== currentConfig.value?.file_path)
    deleteDialogVisible.value = false
    currentConfig.value = null
    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.error('删除失败')
    console.error('Failed to delete config:', error)
  } finally {
    loading.value = false
  }
}

// 预览更改
const previewChanges = () => {
  if (!currentConfig.value || !originalConfig.value) return;

  // 生成当前配置的内容
  previewContent.value = generateConfigContent(currentConfig.value);
  // 生成原始配置的内容
  originalContent.value = generateConfigContent(originalConfig.value);

  previewDialogVisible.value = true;
}

// 撤销更改
const undoChanges = () => {
  if (!currentConfig.value || !originalConfig.value) return;
  currentConfig.value = JSON.parse(JSON.stringify(originalConfig.value));
  hasChanges.value = false;
  changesCount.value = 0;
}

// 在 script 部分添加计算属性
const shouldShowEditor = computed(() => {
  if (!currentConfig.value) return false;
  console.log(!currentConfig.value.servers?.length)
  // 如果没有 upstreams 或者所有 upstream 都没有 servers，或者没有 servers，显示编辑器
  return !currentConfig.value.upstreams?.length &&
         !currentConfig.value.servers?.length;
});

// 在 script 部分添加搜索匹配函数
const getContentMatches = (config: NginxConfigInfo): string => {
  if (!searchQuery.value) return '';
  
  const query = searchQuery.value.toLowerCase();
  const content = config.content.toLowerCase();
  const lines = content.split('\n');
  const matches: number[] = [];
  
  lines.forEach((line, index) => {
    if (line.includes(query)) {
      matches.push(index + 1);
    }
  });
  
  if (matches.length === 0) return '';
  
  // 最多显示前3个匹配位置
  const displayMatches = matches.slice(0, 3);
  const matchText = displayMatches.join(', ');
  return matches.length > 3 
    ? `第 ${matchText} 行等 ${matches.length} 处` 
    : `第 ${matchText} 行`;
};

// 处理删除服务器
const handleDeleteServer = async (row: UpstreamServer, upstream: UpstreamConfig, index: number) => {
  try {
    // await ElMessageBox.confirm('确定要删除此服务器吗？', '警告', {
    //   type: 'warning',
    //   confirmButtonText: '确定',
    //   cancelButtonText: '取消'
    // });

    // 标记为删除而不是直接从数组中移除
    row.isDelete = true;
    
    // 如果是新添加的服务器被删除，减少新增计数
    if (row.isAdd) {
      addUpstreamCount.value--;
      // 新添加的服务器被删除时可以直接从数组中移除
      upstream.servers.splice(index, 1);
    }
    
    // 更新变更计数
    updateChangesCount();
    
    ElMessage.success('服务器已标记删除');
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除服务器失败');
      console.error('Failed to delete server:', error);
    }
  }
}

// 恢复被删除的服务器
const handleRestoreServer = (row: UpstreamServer) => {
  row.isDelete = false;
  updateChangesCount();
  ElMessage.success('服务器已恢复');
}

// 初始化
onMounted(async () => {
  await loadConfigs();
});
</script>

<style scoped>
.nginx-config {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.config-container {
  flex: 1;
  overflow: hidden;
  display: flex;
}

.config-aside {
  height: 100%;
  border-right: 1px solid var(--el-border-color-light);
  display: flex;
  flex-direction: column;
}

.config-list {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.list-header {
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid var(--el-border-color-light);
}

.list-header h3 {
  margin: 0;
}

.search-box {
  padding: 8px 16px;
  border-bottom: 1px solid var(--el-border-color-light);
}

:deep(.search-box .el-input__wrapper) {
  border-radius: 20px;
}

:deep(.search-box .el-input__inner) {
  height: 32px;
}

:deep(.search-box .el-input__prefix) {
  color: var(--el-text-color-secondary);
}

:deep(.el-scrollbar) {
  flex: 1;
}

.config-name {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.config-main {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.config-editor {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 500px;
  border-radius: 10px;
  overflow: hidden;
}

.editor-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  gap: 16px;
  height: 100%;
  position: relative;
}

.editor-header {
  margin-bottom: 10px;
  padding: 10px;
  background-color: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: var(--el-box-shadow-light);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left h2 {
  margin: 0;
  color: var(--el-text-color-primary);
}

.header-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.upstream-section,
.server-block {
  margin-bottom: 20px;
}

.upstream-header,
.server-header {
  padding: 5px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.server-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.domain-name {
  font-weight: bold;
}

.location-block {
  margin-bottom: 16px;
}

.proxy-timeouts {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.changes-bar {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
}

.changes-actions {
  display: flex;
  gap: 8px;
}

:deep(.el-card) {
  margin-bottom: 16px;
}

:deep(.el-descriptions) {
  margin-bottom: 16px;
}

:deep(.el-table) {
  margin-bottom: 16px;
}

.rewrite-rules {
  margin-bottom: 16px;
}

.rewrite-rule {
  display: flex;
  align-items: center;
  gap: 8px;
}

.rewrite-rule .el-icon {
  color: var(--el-text-color-secondary);
}

.try-files {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.try-file-tag {
  margin-right: 4px;
}

.headers {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.header-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-value {
  color: var(--el-text-color-regular);
  font-family: monospace;
}

.server-address {
  display: flex;
  align-items: center;
}

:deep(.server-address .el-input) {
  width: 100%;
}

:deep(.server-address .el-input__inner) {
  font-family: monospace;
}

.failover-settings {
  display: flex;
  gap: 8px;
  align-items: center;

}

:deep(.failover-settings .el-input-number) {
  width: 90px;
}

:deep(.failover-settings .el-input) {
  width: 90px;
}

.content-matches {
  margin-top: 2px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

:deep(.content-matches .el-tag) {
  margin-left: 0;
  font-size: 11px;
  padding: 0 4px;
  height: 20px;
  line-height: 20px;
  background-color: var(--el-fill-color-light);
  border: none;
  border-radius: 2px;
}

:deep(.el-menu-item) {
  flex-direction: column;
  align-items: flex-start;
  height: auto !important;
  min-height: 40px;
  padding: 8px 16px;
  gap: 4px;
  position: relative;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.config-name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
  font-weight: 500;
}

.content-matches {
  margin-top: 2px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

:deep(.content-matches .el-tag) {
  margin-left: 0;
  font-size: 11px;
  padding: 0 4px;
  height: 20px;
  line-height: 20px;
  background-color: var(--el-fill-color-light);
  border: none;
  border-radius: 2px;
}

:deep(.el-menu-item.is-active) {
  background-color: var(--el-color-primary-light-9);
}

:deep(.el-menu-item:hover) {
  background-color: var(--el-fill-color-light);
}

.editor-footer {
  position: absolute;
  bottom: 24px;
  right: 24px;
  z-index: 10;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 0;
  border: none;
  background: transparent;
}

:deep(.editor-footer .el-button) {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  padding: 12px 24px;
}

:deep(.editor-footer .el-button .el-icon) {
  margin-right: 8px;
  font-size: 16px;
}

.visual-config {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

:deep(.visual-config .el-scrollbar) {
  flex: 1;
  height: 100%;
}

:deep(.visual-config .el-scrollbar__wrap) {
  overflow-x: hidden;
}

.visual-content {
  padding: 20px;
}

.changes-bar {
  position: sticky;
  top: 0;
  z-index: 10;
  background: var(--el-bg-color);
  padding: 5px 10px;
  margin-bottom: 0;
  border-bottom: 1px solid var(--el-border-color-light);
}

.changes-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.upstream-section,
.server-block {
  margin-bottom: 20px;
}

.deleted {
  opacity: 0.5;
  pointer-events: none;
}

.deleted :deep(.el-input__inner) {
  text-decoration: line-through;
  color: var(--el-text-color-disabled);
}

.deleted :deep(.el-tag) {
  text-decoration: line-through;
}
</style>